<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
                <el-option label="待支付" :value="0" />
                <el-option label="已确认" :value="1" />
                <el-option label="已发货" :value="2" />
                <el-option label="已收货" :value="3" />
                <el-option label="已退款" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="收货电话" prop="mobile">
              <el-input v-model="queryParams.mobile" placeholder="请输入收货电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="收货地址" prop="address">
              <el-input v-model="queryParams.address" placeholder="请输入收货地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mall:mallOrder:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['mall:mallOrder:edit']">取货码核销</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['mall:mallOrder:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="mallOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单号" align="center" prop="id" v-if="true" width="240px" />
        <el-table-column label="订单号" align="center" prop="orderNo" v-if="false" />
        <el-table-column label="用户ID" align="center" prop="userId" v-if="false" />
        <el-table-column label="订单总额" align="center" prop="totalPrice">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.totalPrice) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="prepayAmount">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.prepayAmount) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="预付金额" align="center" prop="revenue">
          <template #default="scope">
            <div>{{ floatToFixed2(scope.row.revenue) }}元</div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="ter_mall_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="收货人" align="center" prop="consignee" />
        <el-table-column label="收货电话" align="center" prop="mobile" />
        <el-table-column label="收货地址" align="center" prop="address" />
        <el-table-column label="支付方式" align="center" prop="paymentMethod" />
        <el-table-column label="自提点ID" align="center" prop="pickupPointId" v-if="false" />
        <el-table-column label="自提点" align="center" prop="pickupPoint" />
        <el-table-column label="自提码" align="center" prop="pickupCode" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="订单明细" placement="top">
              <el-button link type="primary" icon="Search" @click="handleDetailQuery(scope.row)" v-hasPermi="['mall:mallOrder:Search']"></el-button>
            </el-tooltip>
            <el-tooltip content="退款" placement="top">
              <el-button
                link
                type="primary"
                icon="CreditCard"
                :disabled="scope.row.orderStatus === 0 || scope.row.orderStatus === 4"
                @click="handleDelete(scope.row)"
                v-hasPermi="['tearoom:order:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单主信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="mallOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="id">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="自提码" prop="pickupCode">
          <el-input v-model="form.pickupCode" placeholder="请输入自提码" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option
                v-for="dict in ter_mall_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogDetail.title" v-model="dialogDetail.visible" width="800px">
      <el-table v-loading="loading" border :data="mallOrderitemList" style="width: 100%">
        <!-- 调整列定义 -->
        <el-table-column label="商品名称" prop="productName" />
        <el-table-column label="缩略图" align="center" prop="thumbnailUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.thumbnailUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="price">
          <template #default="{ row }">
            {{ row.price?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" />
        <el-table-column label="总价" prop="totalPrice">
          <template #default="{ row }">
            {{ (row.price * row.quantity)?.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="MallOrder" lang="ts">
import { listMallOrder, getMallOrder, addMallOrder, updateMallOrder, orderRefund } from '@/api/mall/mallOrder';
import { floatToFixed2 } from '@/utils/index';
import { listMallOrderitem } from '@/api/mall/mallOrderitem';
import { MallOrderVO, MallOrderQuery, MallOrderForm } from '@/api/mall/mallOrder/types';
import { MallOrderitemVO } from '@/api/mall/mallOrderitem/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ter_mall_status } = toRefs<any>(proxy?.useDict('ter_mall_status'));
const mallOrderList = ref<MallOrderVO[]>([]);
const originalPickupCode = ref('');
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const mallOrderitemList = ref<MallOrderitemVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const mallOrderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogDetail = reactive<DialogOption>({
  visible: false,
  title: '订单明细查看'
});
const initFormData: MallOrderForm = {
  id: undefined,
  orderNo: undefined,
  userId: undefined,
  totalPrice: undefined,
  prepayAmount: undefined,
  orderStatus: undefined,
  consignee: undefined,
  mobile: undefined,
  address: undefined,
  pickupPointId: undefined,
  pickupCode: undefined,
  pickupPoint: undefined
}
const data = reactive<PageData<MallOrderForm, MallOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    userId: undefined,
    totalPrice: undefined,
    prepayAmount: undefined,
    orderStatus: undefined,
    consignee: undefined,
    mobile: undefined,
    address: undefined,
    pickupPointId: undefined,
    pickupCode: undefined,
    pickupPoint: undefined
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],  
    pickupCode: [
      { required: true, message: "核销码不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单主信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMallOrder(queryParams.value);
  mallOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  mallOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
const detailLoading = ref(false);
const handleDetailQuery = async (row?: MallOrderVO) => {
  try {
    detailLoading.value = true;
    const res = await listMallOrderitem({
      orderId: row?.id,
      pageNum: 1,
      pageSize: 10
    });
    mallOrderitemList.value = res.rows;
    dialogDetail.visible = true;
  } finally {
    detailLoading.value = false;
  }
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const handleDelete = async (row?: MallOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认退回订单编号为"' + _ids + '"的数据项？');
  Object.assign(form.value, row);
  console.log(form.value);
  await orderRefund(form.value);
  await getList();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: MallOrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单主信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MallOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMallOrder(_id);
  Object.assign(form.value, res.data);
  originalPickupCode.value = res.data.pickupCode; // 保存原始取货码
  dialog.visible = true;
  dialog.title = "取货码核销"; // 可根据需要调整对话框标题
}

/** 提交按钮 */
const submitForm = () => {
  mallOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 新增校验逻辑
      if (!originalPickupCode.value) {
        proxy?.$modal.msgError("该订单无有效取货码，无法核销");
        buttonLoading.value = false;
        return;
      }
      if (form.value.pickupCode !== originalPickupCode.value) {
        proxy?.$modal.msgError("核销码不正确");
        buttonLoading.value = false;
        return;
      }

      if (form.value.id) {
        await updateMallOrder(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("核销成功");
      } else {
        await addMallOrder(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("操作成功");
      }
      dialog.visible = false;
      await getList();
    }
  });
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('mall/mallOrder/export', {
    ...queryParams.value
  }, `mallOrder_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
